package cn.edu.sdu.sol.intake_system.service;

import cn.edu.sdu.sol.intake_system.model.po.*;
import cn.edu.sdu.sol.intake_system.model.vo.DataRequest;
import cn.edu.sdu.sol.intake_system.model.vo.DataResponse;
import cn.edu.sdu.sol.intake_system.repository.DepartmentRepository;
import cn.edu.sdu.sol.intake_system.repository.ScoreRepository;
import cn.edu.sdu.sol.intake_system.repository.UserRepository;
import cn.edu.sdu.sol.intake_system.repository.WillRepository;
import cn.edu.sdu.sol.intake_system.utils.JwtUtil;
import cn.edu.sdu.sol.intake_system.utils.PersonInfUtils;
import cn.edu.sdu.sol.intake_system.utils.VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WillService {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserRepository userRepository;

    VO vo = new VO();

    @Autowired
    PersonInfUtils personInfUtils;
    @Autowired
    private WillRepository willRepository;
    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private ScoreRepository scoreRepository;

    public DataResponse changeWill(DataRequest req, String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        Map willList = req.getMap("willList");
        Integer willOrder = (Integer) willList.get("willOrder");
        Integer departmentId = (Integer) willList.get("departmentId");
        // System.out.println(willList);
        // System.out.println(willOrder);
        // System.out.println(departmentId);

        Optional<Department> department = departmentRepository.findDepartmentByDepartmentId(departmentId);
        Department d = new Department();
        if (department.isPresent()) {
            d = department.get();
        } else {
            return vo.messageError("部门不存在");
        }
        //要更改的志愿
        Optional<Will> w = willRepository.findWillListByPersonInfPkAndWillOrder(personId, willOrder);
        //确保志愿不重复
        if (willOrder == 1) {
            Optional<Will> w2 = willRepository.findWillListByPersonInfPkAndWillOrder(personId, 2);
            if (w2.isPresent()) {
                Will will2 = w2.get();
                Department department2 = will2.getDepartment();
                if (department2 == d) {
                    return vo.messageError("两个志愿不能选择相同的部门");
                }
            }
        }
        if (willOrder == 2) {
            Optional<Will> w1 = willRepository.findWillListByPersonInfPkAndWillOrder(personId, 1);
            if (w1.isPresent()) {
                Will will1 = w1.get();
                Department department1 = will1.getDepartment();
                if (department1 == d) {
                    return vo.messageError("两个志愿不能选择相同的部门");
                }
            }
        }
        Will will = new Will();
        Score score = new Score();
        if (w.isPresent()) {
            will = w.get();
            score = will.getScore();
        } else {
            score.setPerson(p);
            scoreRepository.saveAndFlush(score);
            will.setScore(score);
        }
        will.setWillOrder(willOrder);
        will.setDepartment(d);
        will.setPerson(p);
        willRepository.saveAndFlush(will);
        Map data = new HashMap();
        data.put("willId", will.getWillId());
        data.put("DepartmentId", will.getDepartment().getDepartmentId());
        data.put("willOrder", will.getWillOrder());
        return new DataResponse(200, data, "ok");

    }

    public List getWills(Integer personId) {
        List<Will> qList = willRepository.findWillListByPersonInfPk(personId);
        List dataList = new ArrayList();
        if (qList == null || qList.size() == 0) {
            return dataList;
        }
        for (int i = 0; i < qList.size(); i++) {
            Will will = qList.get(i);
            Map m = new HashMap();
            if (will == null) {
                dataList.add(m);
            } else {
                m.put("willOrder", will.getWillOrder());
                m.put("departmentId", will.getDepartment().getDepartmentId());
                dataList.add(m);
            }
        }
        return dataList;
    }

    public DataResponse cancelWill(DataRequest req, String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        Integer willOrder = req.getInteger("willOrder");
        Optional<Will> w = willRepository.findWillListByPersonInfPkAndWillOrder(personId, willOrder);
        if (w.isEmpty()) {
            return vo.messageError("志愿不存在,无法取消");
        }
        Will will = w.get();
        Score score = will.getScore();
        willRepository.delete(will);
        scoreRepository.delete(score);

        List wills = getWills(personId);
        return new DataResponse(200, wills, "ok");
    }

    public DataResponse getApplicationInf(DataRequest req, String token) {
        Integer departmentId = req.getInteger("departmentId");
        Department d = departmentRepository.findDepartmentByDepartmentId(departmentId).get();
        List dataList = new ArrayList();
        List<Will> qList = willRepository.findWillListByDepartmentId(departmentId);
        if (qList == null || qList.size() == 0) {
            return vo.ok();
        }
        for (int i = 0; i < qList.size(); i++) {
            dataList.add(getMapFromWill(qList.get(i)));
        }
        return new DataResponse(200,dataList,"ok");

    }

    private Map<String, Object> getMapFromWill(Will will) {
        Map<String, Object> m = new HashMap<>();
        if (will == null) {
            return m;
        }
//        System.out.println("==========================");
//        System.out.println(will);
//        System.out.println(will.getWillId());
//        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<");
        PersonInf p = will.getPerson();
        Integer departmentId = will.getDepartment().getDepartmentId();
        Integer personId = p.getPersonInfPk();

//        System.out.println("willService 177: personId: "+ personId);

        Optional<SysUser> optionalSysUser = userRepository.findUserByPersonId(personId);
        if(optionalSysUser.isEmpty()){

        }
        Will will1 = new Will();
        Will will2 = new Will();
        String willName1 = null;
        String willName2 = null;
        Optional<Will> will01 = willRepository.findWillListByPersonInfPkAndWillOrder(personId, 1);
        if (will01.isPresent()) {
            will1 = will01.get();
            willName1 = will1.getDepartment().getName();
        }
        Optional<Will> will02 = willRepository.findWillListByPersonInfPkAndWillOrder(personId, 2);
        if (will02.isPresent()) {
            will2 = will02.get();
            willName2 = will2.getDepartment().getName();
        }


        String studentNum = "000000000000";
        if(optionalSysUser.isPresent()){
            studentNum = optionalSysUser.get().getStudentNum();
        }

        m.put("studentNum", studentNum);
        m.put("personId", p.getPersonInfPk());
        m.put("name", p.getName());
        String gender = "未知";
        if(p.getGender() == Gender.MALE){
            gender = "男";
        } else if(p.getGender() == Gender.FEMALE){
            gender = "女";
        }
        m.put("gender", gender);
        m.put("academy", p.getAcademy());
        m.put("qqNum", p.getQqNum());
        m.put("phoneNum", p.getPhoneNum());
        m.put("profession", p.getProfession());
        m.put("birthday", p.getBirthday());
        m.put("email", p.getEmail());
        m.put("introduction", p.getIntroduction());
        m.put("willFirst", willName1);
        m.put("willSecond", willName2);

        Score s = will.getScore();
        m.put("facePassed", s.getFacePassed());
        m.put("penPassed", s.getPenPassed());
        m.put("isPassed", s.getIsPassed());
        m.put("school",p.getSchool());
        m.put("birthPlace",p.getBirthPlace());
        return m;
    }

    public DataResponse getUserWills(String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        List<Will> qList = willRepository.findWillListByPersonInfPk(personId);
        List dataList = new ArrayList();
        if (qList == null || qList.size() == 0) {
            return new DataResponse(200, dataList, "无志愿信息");
        }
        for (int i = 0; i < qList.size(); i++) {
            Will will = qList.get(i);
            Map m = new HashMap();
            if (will == null) {
                dataList.add(m);
            } else {
                m.put("willOrder", will.getWillOrder());
                m.put("departmentId", will.getDepartment().getDepartmentId());
                m.put("departmentName", will.getDepartment().getName());
                m.put("penTime", will.getDepartment().getPenTime());
                m.put("faceTime", will.getDepartment().getFaceTime());
                dataList.add(m);
            }
        }
        return new DataResponse(200,dataList,"ok");
    }


    public DataResponse getResult(DataRequest req, String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        Integer willOrder = req.getInteger("willOrder");
        Optional<Will> will = willRepository.findWillListByPersonInfPkAndWillOrder(personId, willOrder);
        if (will.isEmpty()) {
            return vo.messageError("无");
        }
        Will w = will.get();
        Score sc = w.getScore();
        Map data = new HashMap();
        data.put("willOrder", willOrder);
        data.put("departmentName", w.getDepartment().getName());
        data.put("facePassed", sc.getFacePassed());
        data.put("penPassed", sc.getPenPassed());
        data.put("isPassed", sc.getIsPassed());
        return new DataResponse(200,data,"ok");
    }

    public DataResponse deleteWill(DataRequest req, String token) {
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        assert sysUser.isPresent();
        Integer personId = req.getInteger("personId");
        Integer departmentId = req.getInteger("departmentId");
        Optional<Will> w = willRepository.findWillByPersonInfPkAAndDepartmentId(personId, departmentId);
        if (!w.isPresent()) {
            return vo.messageError("志愿不存在,无法删除");
        }
        Will will = w.get();
        Score score = will.getScore();
        willRepository.delete(will);
        scoreRepository.delete(score);
        List wills = getWills(personId);
        return new DataResponse(200,wills,"ok");
    }

    public DataResponse getAllApplicationInf(DataRequest req) {
        Integer stationId = req.getInteger("stationId");
//        List dataList = new ArrayList();
        List<Map<String, Object>> dataList = new ArrayList<>();

        List<Will> qList = willRepository.findWillListByStationId(stationId);
        if (qList == null || qList.size() == 0) {
            return vo.ok();
        }
//        for (int i = 0; i < qList.size(); i++) {
//            dataList.add(getMapFromWill(qList.get(i)));
//        }

//         使用Stream按照personInfPk进行去重
        dataList = new ArrayList<>(qList.stream()
                .map(this::getMapFromWill)
                .collect(Collectors.toMap(
                        map -> map.get("personId"), // 使用personId作为key
                        map -> map, // 去重时保留原map
                        (existing, replacement) -> existing, // 去重时保留已存在的map
                        HashMap::new // 指定返回的Map类型为HashMap
                ))
                .values());
//        for(Will will: qList){
//            dataList.add(getMapFromWill(will));
//        }

        return new DataResponse(200,dataList,"ok");
    }
}
